package com.example.javaproject.okhttp;

import java.io.File;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.BufferedSink;
import okio.Okio;

public class OKFileUtil {

    public static File synDownloadFile(String url, String destDir, String destName) {
        File resultFile = null;
        try {
            Response response = new OkHttpClient()/* OkHttpUtils.getInstance().getOkHttpClient()*/.newCall(new Request.Builder().url(url).get().build()).execute();
            resultFile = saveToFile(response, destDir, destName);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return resultFile;

    }

    public static File saveToFile(Response response, String destDir, String destName) {
        File dir = new File(destDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        File downloadTempFile = new File(dir, destName + ".temp");
        try (ResponseBody body = response.body();
             BufferedSink bufferedSink = Okio.buffer(Okio.sink(downloadTempFile))) {
            if (body == null) return null;
            bufferedSink.writeAll(body.source());
            bufferedSink.flush();
        } catch (Exception e) {
            e.printStackTrace();
            downloadTempFile.delete();
        }

        if (downloadTempFile.exists()) {
            File actualFile = new File(dir, destName);
            if (downloadTempFile.renameTo(actualFile)) {
                return actualFile;
            }
        }
        return null;
    }

    public static void download(final String url, final String destDir, final String destName) {
        new OkHttpClient()/* OkHttpUtils.getInstance().getOkHttpClient()*/.newCall(new Request.Builder().url(url).get().build()).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println(String.format("downloadFailed:%s dir:%s file:%s", url, destDir, destName));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                saveToFile(response, destDir, destName);
            }
        });

    }
}
